package org.bjf.modules.sys.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import lombok.Data;
import org.bjf.exception.ServiceException;
import org.bjf.modules.core.web.core.LoginInfo;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.enums.SysMsgCode;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.modules.sys.service.SysUserService;
import org.bjf.modules.user.enums.UserRedisKey;
import org.bjf.utils.IpUtil;
import org.bjf.utils.MD5Util;
import org.bjf.utils.RedisUtil;
import org.bjf.utils.TokenUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bjf
 */
@RestController
@Validated
@RequestMapping("admin")
public class SysController {

  @Resource
  private RedisUtil redis;

  @Resource
  private SysUserService sysUserService;

  @RequestMapping("login")
  public LoginResp login(@RequestParam @NotBlank String username,
      @RequestParam @NotBlank String password, HttpServletRequest request) {
    //===1、验证用户名密码
    SysUserQuery query = new SysUserQuery();
    query.setUsername(username);
    SysUser loginUser = sysUserService.getOne(query);
    if (loginUser == null || !MD5Util.validDigest(password, loginUser.getPassword())) {
      throw new ServiceException(SysMsgCode.USER_WRONG);
    }
    //===2、登录成功，生成token并将登录用户信息写入redis
    Long userId = loginUser.getSysUserId();
    String ip = IpUtil.getClientIp(request);
    String accessToken = TokenUtil.genToken(userId, ip);
    String userKey = UserRedisKey.TOKEN_ADMIN.as(accessToken);
    LoginInfo loginInfo = LoginInfo
        .buildLoginInfo(accessToken, userId, loginUser.getUsername(), ip);
    // 15天过期
    long timeout = 60 * 30;
    redis.setex(userKey, loginInfo, timeout);

    //===3、返回登录信息-accessToken
    LoginResp loginResp = new LoginResp();
    loginResp.setAccessToken(accessToken);
    return loginResp;
  }

  @Data
  private static class LoginResp {

    private String accessToken;
  }
}
